<template>
  <div class="form-table">
    <el-form :model="formData" lableAlign="right" labelWidth="125px" ref="formRef" v-bind="$attrs">
      <el-row>
        <el-col :span="item.span" v-for="item in fileds" :key="item.key">
          <el-form-item v-if="item.filedType === 'custom'" :label="item.label" :prop="item.key">
            <slot :name="item.key" :row="formData" />
          </el-form-item>
          <el-form-item v-else :label="item.label" :prop="item.key" :class="isRequired(item) ? 'required' : ''">
            <span v-if="item.disabled">
              <span v-if="item.isTimeFilter">{{ formData[item.key] | timeFilter }}</span>
              <span v-else>{{ item.showKey ? formData[item.showKey] : formData[item.key] }}</span>
            </span>
            <template v-else>
              <component v-show="!item.hidden" :is="item.filedType" size="small" v-bind="item.props" clearable
                v-model="formData[item.key]" />
            </template>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </div>
</template>
<script>
import Input from "./components/Input.vue"
import Select from "./components/Select.vue"
import DatePicker from "./components/DatePicker.vue"
import Radio from "./components/Radio.vue"
import Cascader from "./components/Cascader.vue"
import DateTimePicker from "./components/DateTimePicker.vue"
import dayjs from "dayjs"
export default {
  components: { Input, Select, DatePicker, Radio, Cascader, DateTimePicker },
  props: {
    fileds: {
      type: Array,
      default: () => []
    },
    formData: {
      type: Object,
      default: () => { }
    },
  },
  filters: {
    timeFilter(value) {
      return dayjs(value).format("YYYY-MM-DD HH:mm:ss")
    }
  },
  data() {
    return {
    }
  },
  computed: {
    isRequired() {
      return function (item) {
        if (!item.props || !item.props.rules || item.props.rules.length === 0) return false
        if (item.props.rules.some(rule => rule.required)) return true
        return false
      }
    }
  },
  methods: {
    validate() {
      const arr = []
      // 校验必填项
      this.fileds.forEach(item => {
        const value = this.formData[item.key]
        if (item.props && item.props.rules && item.props.rules.length > 0 && item.props.rules.some(rule => rule.required)) {
          if (value || value === 0 || value === "0") {
            arr.push({ value: true })
          } else {
            const rule = item.props.rules.find(v => v.required)
            arr.push({ value: false, message: rule.message })
          }
        }
      })
      const t = arr.every(v => v.value)
      if (t) {
        return true
      } else {
        const filter = arr.filter(item => !item.value)
        const textArr = filter.map(item => item.message)
        this.$message.error(textArr.join(","))
        return false
      }
    }
  }
}
</script>
